﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using QDT.Common;
using QDT.Core;
using QDT.Core.Deals;
using QDT.Core.Domain;
using QDT.Core.Members;
using QDT.Common.Data;
using QDT.MVC.Security;
using QDT.Services.Deals;
using QDT.Services.Members;
using QDT.Web.Admin.Models;

namespace QDT.Web.Admin.Controllers
{
    [SecurityModule(Name = "会员管理")]
    public class UserController : BaseController
    {
        protected readonly IUserService UserService;
        protected readonly IQureyService QureyService;

        public UserController(IUserService userService, IQureyService qureyService)
        {
            Check.Argument.IsNotNull(userService, "userService");

            UserService = userService;
            QureyService = qureyService;
        }

        [SecurityNode(Name = "会员列表")]
        public ActionResult Index(int? page, GridSortOptions sort, int? userid, string username, string email, string mobile, string realname, int? groupId, DateTime? createTime)
        {
            const int pageSize = 50;
            var pageNumber = page ?? 1;

            var groups = DbProvider.D<UserGroup>().ToList();

            ViewData["UserGroups"] = groups;

            var filter = PredicateExtensionses.True<User>();

            if (createTime != null)
            {
                var startTime = ((DateTime)createTime).Date;
                var emdTime = startTime.AddDays(1);
                filter = filter.And(x => x.CreateTime >= startTime && x.CreateTime < emdTime);
            }

            if (userid.HasValue) filter = filter.And(user => user.ID == userid);
            if (groupId.HasValue && groupId != -1) filter = filter.And(user => user.GroupID == groupId);
            if (!string.IsNullOrWhiteSpace(username)) filter = filter.And(user => user.UserName.Contains(username));
            if (!string.IsNullOrWhiteSpace(email)) filter = filter.And(user => user.Email.Contains(email));
            if (!string.IsNullOrWhiteSpace(mobile)) filter = filter.And(user => user.Mobile.Contains(mobile));
            if (!string.IsNullOrWhiteSpace(realname)) filter = filter.And(user => user.RealName.Contains(realname));

            ViewData["sort"] = sort;
            var source = DbProvider.D<User>().Include(x => x.UserAccount).Where(filter.And(user => !user.IsDelete)).OrderBy(sort.Column,
                                                                                                sort.Direction == SortDirection.Descending);
            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }


        [SecurityNode(Name = "会员回收站")]
        public ActionResult Trash(int? page, GridSortOptions sort)
        {
            const int pageSize = 20;
            var pageNumber = page ?? 1;

            if (sort.Column == null) sort.Column = "ID";

            ViewData["sort"] = sort;
            var source = DbProvider.D<User>().Where(x => x.IsDelete).OrderBy(sort.Column,
                                                                             sort.Direction == SortDirection.Ascending);

            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }

        [SecurityNode(Name = "添加页面")]
        public ActionResult Add()
        {

            ViewData["UserGroup"] = DbProvider.D<UserGroup>().ToList();

            return View();
        }

        /// <summary>
        /// 添加用户（目前只添加借款人，不能添加投资人）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [SecurityNode(Name = "添加会员操作")]
        public ActionResult PostAdd(UserAddModel model)
        {

            if (!ModelState.IsValid) return Error();

            if (model.GroupID <= 0) return Error("请选择一个有效的用户组");

            if (DbProvider.D<User>().Count(x => x.UserName == model.UserName) > 0)
                return Error("用户名已经存在.");

            if (DbProvider.D<User>().Count(x => x.Email == model.Email) > 0)
                return Error("电子邮件已经存在.");

            if (string.IsNullOrWhiteSpace(model.Mobile) && DbProvider.D<User>().Count(x => x.Mobile == model.Mobile) > 0)
                return Error("手机号码已经存在.");

            var group = DbProvider.GetByID<UserGroup>(model.GroupID);

            if (group == null) return Error("用户组无效.");

            var isLeander = false;
            var isBorrower = false;

            if (model.UserType == 0) isBorrower = true; else isLeander = true;

            var borrow = new User(group, model.UserName, model.Email, model.Password, isLeander, isBorrower)
            {
                Mobile = model.Mobile,
                RealName = model.RealName,
                IDCard = model.IDCard,
                BirthYear = model.BirthYear ?? 0,
                BirthMonth = model.BirthMonth ?? 0,
                BirthDay = model.BirthDay ?? 0,
                Sex = model.Sex,
                IsEffect = model.IsEffect,
                IsLender = isLeander,
                IsBorrower = isBorrower,
                CompanyName = model.CompanyName,
                Credentials = model.Credentials
            };

            DbProvider.Add(borrow);
            DbProvider.SaveChanges();

            DbProvider.Add(new UserSta(borrow));
            DbProvider.SaveChanges();

            return Success("操作成功");
        }

        [SecurityNode(Name = "编辑会员页面")]
        public ActionResult Edit(int id)
        {
            var user = DbProvider.GetByID<User>(id);
            if (user == null) return Error("会员不存在");

            user.UserSta = UserService.UserSta(user.UserName);

            ViewData["UserGroup"] = DbProvider.D<UserGroup>().ToList();

            return View(user);
        }

        [HttpPost]
        [SecurityNode(Name = "编辑会员操作")]
        public ActionResult PostEdit(UserEditModel model)
        {
            if (!ModelState.IsValid) return Error();

            if (model.GroupID <= 0) return Error("请选择一个有效的用户组");

            if (string.IsNullOrWhiteSpace(model.Mobile) && DbProvider.D<User>().Count(x => x.Mobile == model.Mobile && x.ID != model.ID) > 0)
                return Error("手机号码已经存在.");

            if (DbProvider.D<UserGroup>().Count(x => x.ID == model.GroupID) == 0) return Error("用户组无效.");

            var user = DbProvider.GetByID<User>(model.ID);

            if (user == null) return Error("用户不存在.");

            user.Mobile = model.Mobile;
            if (!string.IsNullOrWhiteSpace(model.Password)) user.ChangePassword(model.Password);
            if (!string.IsNullOrWhiteSpace(model.SafePassword)) user.ChangeSafePassword(model.SafePassword);
            user.GroupID = model.GroupID;
            user.RealName = model.RealName;
            user.IDCard = model.IDCard;
            user.BirthYear = model.BirthYear ?? 0;
            user.BirthMonth = model.BirthMonth ?? 0;
            user.BirthDay = model.BirthDay ?? 0;
            user.Sex = model.Sex;
            user.IsEffect = model.IsEffect;
            user.CompanyName = model.CompanyName;
            user.Credentials = model.Credentials;
            if (!model.IDCardPassed)
            {
                user.ClearIDCard();
            }
            if (model.IDCardPassed && !string.IsNullOrWhiteSpace(model.RealName) && !string.IsNullOrWhiteSpace(model.IDCard))
            {
                user.BindIDCard(model.IDCard, model.RealName);
            }
            if (model.UserType == 0)
            {
                user.IsBorrower = true;
                user.IsLender = false;
            }
            else
            {
                user.IsBorrower = false;
                user.IsLender = true;
            }

            Logs("编辑用户： {0}", user.UserName);

            DbProvider.SaveChanges();

            return Success("操作成功");
        }

        [HttpPost]
        [SecurityNode(Name = "删除会员操作")]
        public ActionResult Delete(int[] id)
        {
            if (id == null) return Error("未选择用户");

            foreach (var i in id)
            {
                var user = DbProvider.GetByID<User>(i);

                user.IsDelete = true;

            }

            DbProvider.SaveChanges();
            return Success("操作成功");
        }


        [SecurityNode(Name = "永久会员删除")]
        [HttpPost]
        public ActionResult ForeverDel(int[] id)
        {
            if (id == null || id.Count() == 0) return Error("未选择用户");

            foreach (var i in id)
            {
                var user = DbProvider.GetByID<User>(i);

                if (user == null) continue;

                DbProvider.Delete(user);
            }

            DbProvider.SaveChanges();

            return Success("操作成功");
        }
        [SecurityNode(Name = "管理员充值列表")]
        public ActionResult AdminCharge(int? page, GridSortOptions sort, int? userid, string username, string realname, DateTime? createTime)
        {
            const int pageSize = 50;
            var pageNumber = page ?? 1;

            var filter = PredicateExtensionses.True<UserOfflineCarry>();

            if (createTime != null)
            {
                var startTime = ((DateTime)createTime).Date;
                var emdTime = startTime.AddDays(1);
                filter = filter.And(x => x.CreateTime >= startTime && x.CreateTime < emdTime);
            }

            if (userid.HasValue) filter = filter.And(user => user.ID == userid);

            if (!string.IsNullOrWhiteSpace(username)) filter = filter.And(user => user.UserName.Contains(username));
            if (!string.IsNullOrWhiteSpace(realname)) filter = filter.And(user => user.RealName.Contains(realname));

            ViewData["sort"] = sort;
            var source = DbProvider.D<UserOfflineCarry>().Where(filter).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);
            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }
        [SecurityNode(Name = "编辑账户")]
        public PartialViewResult Account(int id)
        {
            var dsfdas = System.Web.HttpContext.Current.User.Identity.Name;
            var user = DbProvider.GetByID<User>(id);

            return PartialView(user);
        }

        [HttpPost]
        [SecurityNode(Name = "编辑账户操作")]
        public ActionResult PostAccount(int id, decimal money = 0, int point = 0, decimal quota = 0, decimal experience = 0, decimal offLineCharge = 0, string msg = "")
        {

            var user = DbProvider.GetByID<User>(id);

            if (user == null) return Error("用户不存在");
            var admin = DbProvider.D<AdminUser>().Single(x => x.Name == (System.Web.HttpContext.Current.User.Identity.Name));
            if (admin == null) return Error("管理员信息错误");
            var offIlinCharge = new UserOfflineCarry(user, money, OffLineCarryStatus.Check, admin, msg);
            user.UserAccount.ExpMoney += experience;
            //            user.UserAccount.Quota += quota;
            //            user.UserAccount.Point += point;


            DbProvider.Add(offIlinCharge);
            DbProvider.SaveChanges();

            return Success("操作成功");
        }

        public ActionResult AccountDetail(int id, int? page, GridSortOptions sort)
        {

            var user = DbProvider.GetByID<User>(id);

            if (user == null) return Error("用户不存在");

            ViewData["User"] = user;

            const int pageSize = 20;
            var pageNumber = page ?? 1;

            if (sort.Column == null)
            {
                sort.Column = "ID";
                sort.Direction = SortDirection.Descending;
            }

            ViewData["sort"] = sort;

            var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == id).OrderBy(sort.Column,

                                                                 sort.Direction == SortDirection.Ascending);

            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }

        [HttpPost]
        public ActionResult DeleteLog(int[] id)
        {

            UserService.DeleteUserLog(id);

            return Success("操作成功");
        }

        [SecurityNode(Name = "账户变动明细")]
        public ActionResult ChangeList(int? page, GridSortOptions sort, DateTime? time, string info)
        {
            const int pageSize = 50;
            var pageNumber = page ?? 1;

            var filter = PredicateExtensionses.True<UserTransLog>();

            if (time != null)
            {
                var startTime = ((DateTime)time).Date;
                var endTime = startTime.AddDays(1);
                filter = filter.And(x => x.Time >= startTime && x.Time < endTime);
            }

            if (!string.IsNullOrWhiteSpace(info))
            {
                filter = filter.And(x => x.Info.Contains(info));
                if (info.Contains("偿还") && time.HasValue)
                {
                    ViewBag.RepayMoney = QureyService.GetUserRepayMoney(time.Value);
                }
            }

            ViewData["sort"] = sort;
            var source = DbProvider.D<UserTransLog>().Where(filter).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);
            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }

        [SecurityNode(Name = "账户每日统计")]
        public ActionResult UserDailySta(int? page)
        {
            const int pageSize = 10;
            var pageNumber = page ?? 1;
            var source = DbProvider.D<DailyStatistics>().OrderByDescending(x => x.ID);
            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }

        public ActionResult AutoBidList(int? page)
        {
            const int pageSize = 20;
            var pageNumber = page ?? 1;
            var source = DbProvider.D<UserAutoBid>().OrderByDescending(x => x.ID);
            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }

        public ActionResult AutoBidSta(int? page, DateTime? date)
        {
            if (!date.HasValue) date = DateTime.Now;
            var start = date.Value.Date;
            var end = start.AddDays(1);
            const int pageSize = 20;
            var pageNumber = page ?? 1;
            var source = DbProvider.D<Credit>().Where(x => x.CreateTime >= start && x.CreateTime < end && x.IsAuto).OrderByDescending(x => x.ID);

            ViewData["Total"] = DbProvider.D<Credit>().Where(x => x.CreateTime >= start && x.CreateTime < end && x.IsAuto).ToList().Sum(x => x.BuyMoney).ToMoney();

            return View(source.ToPagedList(pageNumber - 1, pageSize));
        }
        [SecurityNode(Name = "新增投资人")]
        public ActionResult NewInvester(int? page, DateTime? date)
        {
            if (!date.HasValue) date = DateTime.Now.Date;
            var result = QureyService.GetNewInvester(date.Value);
            ViewData["InvesterCount"] = QureyService.GetInvesterCount();
            return View(result);
        }

        public ActionResult UserSta(int id)
        {
            var user = DbProvider.GetByID<User>(id);
            if (user == null) return Error("无效ID");
            UserService.UserSta(user);
            return Success("操作成功");
        }

    }
}